package indi.juzhuohan.chatroom.client;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.Socket;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import indi.juzhuohan.chatroom.entity.ChatStatus;
import indi.juzhuohan.chatroom.entity.FontStyle;
import indi.juzhuohan.chatroom.entity.TransferInfo;
import indi.juzhuohan.chatroom.io.IOStream;
import indi.juzhuohan.chatroom.util.FontSupport;

/***
 * 聊天界面
 * 
 * @author 鞠卓瀚
 */
public class Chatframe extends JFrame {
//	长、宽的值；背景地址
	private static final long serialVersionUID = 2998610278296864941L;
	public static final Integer FRAME_WIDTH = 750;
	public static final Integer FRAME_HEIGHT = 600;
	private static final String Background_Path = "G:\\java\\chatroom_socket\\src\\indi\\juzhuohan\\chatroom\\client\\chat_background.jpg";
	private static final String Emoji_Path = "G:\\java\\chatroom_socket\\src\\indi\\juzhuohan\\chatroom\\client\\face.png";
	private static final String Jitter_Path = "G:\\java\\chatroom_socket\\src\\indi\\juzhuohan\\chatroom\\client\\jitter.png";
	private static final String Font_choose_Path = "G:\\java\\chatroom_socket\\src\\indi\\juzhuohan\\chatroom\\client\\font_choose.png";
//	接收框
	public JTextPane acceptPane;
//	当前在线用户列表
	public JList lstUser;
	Socket socket;
	String userName;
	JComboBox fontFamilyCmb;
	JComboBox<Integer> fontSizeCmb;
	JComboBox reciverBox;
	Color color;

	public Chatframe(String userName, Socket socket) {
		this.userName = userName;
		this.socket = socket;
//		窗口初始化设置
		this.setTitle(userName + "欢迎来到聊天室");
		setSize(FRAME_WIDTH, FRAME_HEIGHT);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int width = screenSize.width;
		int height = screenSize.height;
		setLocation((width - FRAME_WIDTH) / 2, (height - FRAME_HEIGHT) / 2);
//		背景图
		ImageIcon imageIcon = new ImageIcon(Background_Path);
		JLabel frameBg = new JLabel(imageIcon);
		frameBg.setBounds(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
		this.add(frameBg);
//		聊天记录框
		acceptPane = new JTextPane();
		acceptPane.setOpaque(false);
		acceptPane.setFont(new Font("黑体", 0, 18));
//		接受框滚动条
		JScrollPane scoPaneOne = new JScrollPane(acceptPane);
		scoPaneOne.setBounds(15, 20, 550, 332);
		scoPaneOne.setOpaque(false);
		scoPaneOne.getViewport().setOpaque(false);
		frameBg.add(scoPaneOne);

//		声明菜单
		JPopupMenu popupMenu = new JPopupMenu();

//		用户列表
		lstUser = new JList();
		lstUser.setFont(new Font("黑体", 0, 16));
		lstUser.setVisibleRowCount(17);
		lstUser.setFixedCellWidth(90);
		lstUser.setFixedCellHeight(18);
//		添加点击事件，（需要确认是右键）
		lstUser.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// 监听是左键还是邮件
				if (e.isMetaDown()) {
					// 弹出菜单,JavaScript JS
					popupMenu.show(lstUser, e.getX(), e.getY());
				}
			}
		});
//		滚动面板
		JScrollPane spUser = new JScrollPane(lstUser);
		spUser.setFont(new Font("黑体", 0, 16));
		spUser.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		spUser.setBounds(570, 17, 160, 535);
		frameBg.add(spUser);

//		私聊按钮（菜单项）
		JMenuItem privateChat = new JMenuItem("私聊");
		privateChat.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// 告诉发送消息的接收人是谁？
				Object reciverObj = lstUser.getSelectedValue();
				if (reciverObj != null) {
					String reciver = String.valueOf(reciverObj);
					reciverBox.removeAllItems();
					reciverBox.addItem("所有人");
					reciverBox.addItem(reciver);
					reciverBox.setSelectedItem(reciver);
				}

			}
		});
		popupMenu.add(privateChat);

//		聊天输入框
		JTextPane sendPane = new JTextPane();
		sendPane.setOpaque(false);
		sendPane.setFont(new Font("黑体", 0, 18));
		sendPane.requestFocusInWindow();
		JScrollPane scoPane = new JScrollPane(sendPane);
		scoPane.setBounds(15, 400, 550, 150);
		scoPane.setOpaque(false);
		scoPane.getViewport().setOpaque(false);
		frameBg.add(scoPane);

//		表情包入口
		JLabel lblface = new JLabel(new ImageIcon(Emoji_Path));
		lblface.setBounds(14, 363, 25, 25);
		lblface.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				FaceFrame face = new FaceFrame(sendPane);
			}
		});
		frameBg.add(lblface);

//		抖动
		JLabel lbldoudong = new JLabel(new ImageIcon(Jitter_Path));
		lbldoudong.setBounds(43, 363, 25, 25);
		lbldoudong.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
//				抖动功能实现
				TransferInfo tfi = new TransferInfo();
				tfi.setStatusEnum(ChatStatus.DD);
//				发送人
				tfi.setSender(userName);
//				接收人
				String reciver = "所有人";
				Object reciverObj = reciverBox.getSelectedItem();
				if (reciverObj != null) {
					reciver = String.valueOf(reciverObj);
				}
				tfi.setReciver(reciver);
				IOStream.writeMessage(socket, tfi);
			}
		});
		frameBg.add(lbldoudong);

//		选择字体按钮
		JLabel lblfontChoose = new JLabel(new ImageIcon(Font_choose_Path));
		lblfontChoose.setBounds(44, 363, 80, 25);
		lblfontChoose.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				JColorChooser colorChooser = new JColorChooser();
				color = colorChooser.showDialog(Chatframe.this, "字体颜色", Color.BLACK);
//				字体改变
				FontSupport.setFont(sendPane, color, fontFamilyCmb.getSelectedItem().toString(), Font.BOLD,
						Integer.parseInt(fontSizeCmb.getSelectedItem().toString()));
			}
		});
		frameBg.add(lblfontChoose);

//		字体下拉框
		fontFamilyCmb = new JComboBox();
		GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		String[] str = graphicsEnvironment.getAvailableFontFamilyNames();
		for (String string : str) {
			fontFamilyCmb.addItem(string);
		}
		fontFamilyCmb.setSelectedItem("黑体");
		fontFamilyCmb.setBounds(104, 363, 130, 25);
		System.out.println(fontFamilyCmb.getSelectedItem());
		frameBg.add(fontFamilyCmb);

//		字体大小
		fontSizeCmb = new JComboBox();
		int[] fontsizeIntegers = { 5, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 34, 38, 40 };
		for (int i = 0; i < fontsizeIntegers.length; i++) {
			fontSizeCmb.addItem(fontsizeIntegers[i]);
		}
		fontSizeCmb.setSelectedItem(18);
		fontSizeCmb.setBounds(240, 363, 80, 25);
		frameBg.add(fontSizeCmb);

//		下拉选择框
		reciverBox = new JComboBox();
		reciverBox.setSelectedItem("所有人");
		reciverBox.addItem("所有人");
		reciverBox.setBounds(330, 363, 90, 25);
		frameBg.add(reciverBox);

//		发送按钮
		JButton send = new JButton("发送");
		send.setBounds(440, 360, 125, 32);
		send.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (sendPane.getText().contentEquals("")) {
					JOptionPane.showMessageDialog(send, "输入内容不能为空", "发送失败", JOptionPane.WARNING_MESSAGE);
				} else {
					TransferInfo tfi = new TransferInfo();
//					封装消息
					List<FontStyle> fontStyles = FontSupport.fontEncode(sendPane);
					tfi.setContent(fontStyles);
//					发送人
					tfi.setSender(userName);
//					接收人
					String reciver = "所有人";
					Object reciverObj = reciverBox.getSelectedItem();
					if (reciverObj != null) {
						reciver = String.valueOf(reciverObj);
					}
					tfi.setReciver(reciver);
//					本次处理的消息类型为登录
					tfi.setStatusEnum(ChatStatus.CHAT);
					IOStream.writeMessage(socket, tfi);
					sendPane.setText("");
				}
			}
		});
		send.setFont(new Font("黑体", 0, 20));
		frameBg.add(send);

		// 客户端关闭窗体退出
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					TransferInfo tfi = new TransferInfo();
					tfi.setStatusEnum(ChatStatus.QUIT);
					tfi.setUserName(userName);
					tfi.setNotice(" >>> " + userName + " 已离开聊天室.....");
					IOStream.writeMessage(socket, tfi);
				} catch (Exception e1) {
					System.out.println("chatframe.windowclose");
				}
			}
		});

		setVisible(true);
	}

}
